package com.cwj.io.bio;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.CharBuffer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author: Chenwujie
 * @date: 2021-05-19 13:46
 */
public class ServerSocketTest {
    private static int port = 9232;
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(port);
        ExecutorService executorService = Executors.newCachedThreadPool();

        while(true){
            Socket clientSocket = serverSocket.accept();
            executorService.execute(new Worker(clientSocket));
        }

    }

    public static class Worker implements Runnable{
        private final Socket clientSocket;

        public Worker(Socket clientSocket) {
            this.clientSocket = clientSocket;
        }

        @Override
        public void run() {
            try {
                task(clientSocket);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void task(Socket clientSocket) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
        CharBuffer allocate = CharBuffer.allocate(1024);
        int read = 0;
        String response;
        while((read = reader.read(allocate)) != 0){
            allocate.flip();
            System.out.println("c: " + allocate.toString());
            if("Done".equals(allocate.toString())){
                break;
            }
            response = processRequest(allocate.toString());
            printWriter.println(response);
            System.out.println("to: " + response);
        }
    }

    private static String processRequest(String request) {
        return request;
    }

}
